package com.example.security;

import com.example.entity.User;
import com.example.service.UserService;
import com.example.util.CustomConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    UserService userService;

    @Override
    public UserDetails loadUserByUsername(String idOrPhone) throws UsernameNotFoundException {
        // 根据用户名查找User对象
        User user = userService.getByIdOrPhone(idOrPhone);
        if (user == null) {
            throw new UsernameNotFoundException(CustomConstant.MESSAGE_PASSWORD_ERROR);
        }
        // 给Admin设置角色权限信息
        List<GrantedAuthority> authorities = new ArrayList<>();
        // 获取绑定id
        String role = user.getRole();
        if ("学生".equals(role)) {
            String studentId = userService.getStudentId(user.getId());
            user.setBindId(studentId);
        } else if ("教师".equals(role)) {
            String teacherId = userService.getTeacherId(user.getId());
            user.setBindId(teacherId);
        }
        authorities.add(new SimpleGrantedAuthority("ROLE_" + role));
        return new SecurityUser(user, authorities);
    }
}
